<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Rag Hu
 * Created Time: 2019/7/26 15:35
 * Modified Time: 2019/7/26 15:35
 * Version: 2.0
 */

namespace App\Modules\Partner\Criterias;


use App\Lib\Facades\FLAuth;
use Flower\Core\Repository\Contracts\RepositoryInterface;
use Flower\Core\Repository\Criterias\BaseCriterias;
use Illuminate\Support\Facades\DB;

class GetStandardIndexCriteria extends BaseCriterias
{
    public function apply($model, RepositoryInterface $repository)
    {


        $user_id = FLAuth::id();

        $order_query = DB::table('order')
            ->selectRaw('count(*) as order_num,count(payment=6) as member_card_pay,store_id')

            ->groupBy('store_id');

        $member_card_query = DB::table('member_card')
            ->selectRaw('count(*) as member_card_num,store_id')
            ->groupBy('store_id');


        $select = [
            'hx_user_account.ranking',
            'IFNULL(sum(hx_order.order_num),0) as order_num',
            'IFNULL(sum(hx_order.member_card_pay),0) as member_card_pay',
            'IFNULL(sum(hx_member_card.member_card_num),0) as member_card_num',
            'hx_city.name as city_name'
        ];

        $select = implode($select, ',');

        $model = $model->selectRaw($select)
            ->leftJoin('user_account','user_store.uid','user_account.user_id')
            ->leftJoin(\DB::raw("({$order_query->toSql()}) as hx_order"), function ($join) use ($order_query) {
                $join->mergeBindings($order_query)->on('user_store.sid', '=', 'order.store_id');
            })
            ->leftJoin(\DB::raw("({$member_card_query->toSql()}) as hx_member_card"), function ($join) use ($member_card_query) {
                $join->mergeBindings($member_card_query)->on('user_store.sid', '=', 'member_card.store_id');
            })
            ->leftJoin('store','user_store.sid','store.id')
            ->leftJoin('city','store.adcode','city.code')
            ->where('user_store.uid', $user_id)
            ->where('user_store.rid', 1)
            ->groupBy('user_store.uid');

        return $model;
    }
}